package org.enwey.icarenew.Component;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import org.enwey.icarenew.APPUtils.ToastUtil;
import org.enwey.icarenew.R;

/**
 * Created by John on 2/7/2015.
 */
public class NewHeaderView extends LinearLayout {
    private WebView webView;
    private String mPath;

    public NewHeaderView(Context context) {
        super(context);
        initView();
    }

    public NewHeaderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    private void initView() {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.new_detail_header, this);
        findView(view);
    }

    private void findView(View view) {
        webView = (WebView) view.findViewById(R.id.activity_newdetail_web);
    }

    private void setDetailToWeb(WebView mWeb, String path) {
        WebSettings settings = mWeb.getSettings();
        mWeb.loadUrl(path);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(true);
        mWeb.setBackgroundColor(0);
        Drawable background = mWeb.getBackground();

        if (background != null) {
            background.setAlpha(0);
        }

        mWeb.setWebViewClient(new MyWebViewClient());
    }

    public class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            if (errorCode != 200) {
                ToastUtil.show(getContext(), "网络异常，请检查网路!");
                return;
            }
        }
    }

    public void setPath(String path) {
        if (!TextUtils.isEmpty(path)) {
            mPath = path;
        }else {
            mPath = "http://icarenew.sinaapp.com";
        }
        setDetailToWeb(webView, mPath);
    }
}
